package com.woniuxy.shirocore;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class MyRealmDemo extends AuthorizingRealm {
    //避免魔法值
    private final String REALMNAME="MyRealmDemo";
    /*授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //判断数据是否是下面的认证返回传入的
        if (principals.getRealmNames().contains(REALMNAME)){
            //username来自于下方的return的SimpleAuthenticationInfo中封装的数据
            String username = principals.getPrimaryPrincipal()+"";
            //将角色封装到set可以去重
            Set<String> roles = new HashSet<>();
            roles.add("admin");
            roles.add("manager");
            roles.add("tourist");
            Set<String> perms = new HashSet<>();//封装权限
            perms.add("manager:add");
            perms.add("manager:edit");
            perms.add("manager:del");
            perms.add("manager:find");
            //将查询出来的数据封装到AuthorizationInfo中
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.setRoles(roles);
            simpleAuthorizationInfo.setStringPermissions(perms);
            return simpleAuthorizationInfo;
        }
        return null;
    }
    /*认证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token instanceof UsernamePasswordToken){
            //通过token获取校长
            UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
           //拿到用户信息
            String username = usernamePasswordToken.getUsername();
            String password = "123456";
            //判断登陆的密码是否和传入的密码一致
            if (new String(usernamePasswordToken.getPassword()).equals(password)){
                System.out.println("登陆成功");
                //将用户名，密码域名封装到SimpleAuthenticationInfo
                return new SimpleAuthenticationInfo(username,password,REALMNAME);
            }else {
                return null;
            }
        }
        return null;
    }
}
